<html>
<head>
<link rel="shortcut icon" href="./favicon.ico">
<link rel="stylesheet" type="text/css" href="./style.css">
<link rel="canonical" href="./CarryIn_Binary.html">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Given two *binary* signed or unsigned integers (`A` and `B`) and their sum or difference (`sum`), returns the carry-in which happened at each bit position during the addition or subtraction.  You can use this on any matching subset of bits of `A`, `B`, and `sum`.">
<title>CarryIn Binary</title>
</head>
<body>

<p class="inline bordered"><b><a href="./CarryIn_Binary.v">Source</a></b></p>
<p class="inline bordered"><b><a href="./legal.html">License</a></b></p>
<p class="inline bordered"><b><a href="./index.html">Index</a></b></p>

<h1>Binary Carry-In Calculator</h1>
<p>Given two <em>binary</em> signed or unsigned integers (<code>A</code> and <code>B</code>) and their sum
 or difference (<code>sum</code>), returns the carry-in which happened at each bit
 position during the addition or subtraction.  You can use this on any
 matching subset of bits of <code>A</code>, <code>B</code>, and <code>sum</code>.</p>
<p>Figuring out the carry-ins has uses for sub-word bit-parallel computations,
 such as determining if a vector byte addition overflowed into the adjacent
 byte, but the main use is to get the carry-in <em>into</em> the most-significant
 bit of a sum. Comparing the final carry-in with the final carry-out allows
 us to determine if a signed overflow occured, and to <a href="./Arithmetic_Predicates_Binary.html">compute other
 arithmetic predicates</a> (e.g.:
 less-than, greater-than-or-equal, etc...)</p>

<pre>
`default_nettype none

module <a href="./CarryIn_Binary.html">CarryIn_Binary</a>
#(
    parameter WORD_WIDTH = 0
)
(
    input   wire    [WORD_WIDTH-1:0]    A,
    input   wire    [WORD_WIDTH-1:0]    B,
    input   wire    [WORD_WIDTH-1:0]    sum,
    output  reg     [WORD_WIDTH-1:0]    carryin
);

    initial begin
        carryin = {WORD_WIDTH{1'b0}};
    end
</pre>

<p>Re-add the two integers without carries, which is merely XOR, then compare
 that carry-less sum with the input <code>sum</code> (this is also an XOR). If the sums
 differ, then a carry-in was present at that bit position during the input
 <code>sum</code>.</p>

<pre>
    always @(*) begin
        carryin = A ^ B ^ sum;
    end

endmodule
</pre>

<hr>
<p><a href="./index.html">Back to FPGA Design Elements</a>
<center><a href="https://fpgacpu.ca/">fpgacpu.ca</a></center>
</body>
</html>

